package com.lxb.myblog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lxb.myblog.po.Tag;
import com.lxb.myblog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/tags")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("")
    public String tags(Model model, @RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum) {
        PageHelper.startPage(pageNum, 10);
        List<Tag> tags = tagService.getAllTag();
        PageInfo<Tag> pageInfo = new PageInfo<>(tags);
        model.addAttribute("pageInfo", pageInfo);
        return "admin/tags";
    }

    @GetMapping("/input")
    public String input(Model model) {
        model.addAttribute("tag", new Tag());
        return "admin/tags-input";
    }

    @GetMapping("/input/{id}")
    public String editInput(@PathVariable Integer id, Model model) {
        model.addAttribute("tag", tagService.getTagById(id));
        return "admin/tags-input";
    }

    @PostMapping("/add")
    public String add(Tag tag, RedirectAttributes attributes) {
        int result;
        if (tag.getId() != null) {
            result = tagService.updateTag(tag);
        } else {
            result = tagService.saveTag(tag);
        }

        if (result != 1) {
            // 更新或保存失败
            attributes.addFlashAttribute("message", "更新或保存失败");
        } else {
            // 更新或保存成功
            attributes.addFlashAttribute("message", "更新或保存成功");
        }

        return "redirect:/admin/tags";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        tagService.deleteTag(id);
        return "redirect:/admin/tags";
    }
}
